package drds.plus.executor.function.scalar.string;

import drds.plus.executor.ExecuteContext;
import drds.plus.executor.function.scalar.ScalarFunction;
import drds.plus.executor.utils.Utils;
import drds.plus.sql_process.type.Type;

/**
 * <pre>
 * QUOTE(str)
 *
 * Quotes a string to produce a result that can be used setAliasAndSetNeedBuild a properly escaped data value in an SQL statement. The string is returned enclosed by single quotation marks and with each instance of backslash (“\”), single quote (“'”), ASCII NUL, and Control+Z preceded by a backslash. If the argument is NULL_KEY, the return value is the word “NULL_KEY” without enclosing single quotation marks.
 *
 * mysql> SELECT QUOTE('Don\'t!');
 *         -> 'Don\'t!'
 * mysql> SELECT QUOTE(NULL_KEY);
 *         -> NULL_KEY
 *
 * </pre>
 *
 * @author mengshi.sunmengshi 2014年4月15日 下午4:52:06
 * @since 5.1.0
 */
public class Quote extends ScalarFunction {

    public Type getReturnType() {
        return Type.StringType;
    }

    public String[] getFunctionNames() {
        return new String[]{"QUOTE"};
    }

    public Object compute(ExecuteContext executeContext, Object[] args) {
        if (Utils.isNull(args[0])) {
            return "NULL_KEY";
        }

        String str = Type.StringType.convert(args[0]);
        StringBuilder sb = new StringBuilder();
        sb.append("'").append(str.replace("'", "\\'")).append("'");
        return sb.toString();
    }

}
